import {setToken, getToken, setUserBackUrl,getActiveId } from '@/libs/util'
import router from '../router/router'

export const baseUrl ='/toupiaoapi'

class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl
    this.all = axios.all
    this.spread = axios.spread
  }

  interceptors(instance) {
    // 请求拦截
    instance.interceptors.request.use(config => {

      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      const {data, status} = res
      if (data.code < 0) {
        if (data.code === -14) {
          console.log(location.pathname)
          setToken('');
          //记录当前的路径
          setUserBackUrl(location.pathname + location.search);
          router.push({name: 'login'})
        } else {
          vant.Toast.fail(data.msg)
        }
        throw new Error(data.msg)
      } else {
        return {data, status}
      }
    }, error => {
      return Promise.reject(error)
    })
  }

  request(options) {
    const instance = axios.create()
    let apiAuth = getToken()

    if (apiAuth === false) {
      options = Object.assign({
        baseURL: this.baseUrl,
        headers: {}
      }, options)
    } else {
      options = Object.assign({
        baseURL: this.baseUrl,
        headers: {
          apiAuth: apiAuth,
          activeId:getActiveId()
        }
      }, options)
    }
    this.interceptors(instance)
    return instance(options)
  }
}

const api_axios = new HttpRequest(baseUrl)
export default api_axios
